<template>
    <div class="app-container normalFormBg">
      <div class="dataManage bgFF">
        <div class="dataManageTop pageFlex pageSpaceBetween">
          <div class="itemBox" :class="{'active': form.validated >= 0}">
            填写资质信息
            <div class="sanBox"></div>
          </div>
          <div class="itemBox" :class="{'active': form.validated >= 1}">
            {{ form.validated === '2' ? '资质审核失败请重新提交' : '等待资质审核' }}
            <div class="whiteSanBox"></div>
            <div class="sanBox"></div>
          </div>
          <div class="itemBox" :class="{'active': form.validated === '3'}">
            完成资料录入
            <div class="whiteSanBox"></div>
          </div>
        </div>
        <el-form
          ref="formRef"
          class="dataManageContent"
          :model="form"
          :disabled="['1', '3'].includes(form.validated)"
          :rules="rules"
          label-width="200">
          <div class="normalBox">
            <div class="titleBox pageFlex pageAlignCenter">
              <div class="line"></div>
              <div class="title">基本信息</div>
            </div>
            <div class="contentBox bgFF">
              <el-form-item label="公司LOGO" prop="thumb">
                <div class="imgBox">
                  <ImageUpload v-model="form.thumb" bg="#FFFFFF"></ImageUpload>
                </div>
              </el-form-item>
              <el-form-item label="公司名称" prop="companyName">
                <el-input
                  class="inputBox"
                  v-model="form.companyName"
                  placeholder="请输入公司名称"
                  :maxlength="50"
                  clearable
                />
              </el-form-item>
              <el-form-item label="公司类型" prop="companyType">
                <el-select class="inputBox" v-model="form.companyType" placeholder="请选择公司类型" clearable>
                  <el-option v-for="dict in meter_company_type" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="统一社会信用代码" prop="creditCode">
                <el-input
                    class="inputBox"
                    v-model="form.creditCode"
                    placeholder="请输入统一社会信用代码"
                    clearable
                />
              </el-form-item>
              <el-form-item label="所属区域" prop="location">
                <SelectOption class="selectOptionBox" ref="locationSelectOption" placeHolder="请选择所属区域" title="区域选择"
                    v-model="form.location" selectType="multi" maxSelectLength="3" treeNodeKey="name" :defaultFormValue="locationDefault" :disabled="['1', '3'].includes(form.validated)"
                    @loadOptions="locationDataLoad" @chooseError="locationChooseError" @chooseConfirm="locationChooseConfirm" v-if="!pageLoading"/>
              </el-form-item>
              <el-form-item label="公司规模" prop="size">
                <el-input
                    class="inputBox"
                    type="number"
                    v-model="form.size"
                    placeholder="请输入公司规模"
                    clearable
                >
                  <template #suffix>
                    <div>人</div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="公司主要经营范围" prop="business">
                <el-input
                    class="textareaBox"
                    v-model="form.business"
                    type="textarea"
                    :rows="6"
                    placeholder="请输入公司主要经营范围"
                />

              </el-form-item>
              <el-form-item label="经营模式" prop="mode">
                <el-input
                    class="inputBox"
                    v-model="form.mode"
                    placeholder="请输入经营模式（企业机构类型）"
                    clearable
                />
              </el-form-item>
              <el-form-item label="公司注册日期" prop="regyear">
                <el-date-picker
                    v-model="form.regyear"
                    type="date"
                    placeholder="请选择公司注册日期"
                    style="width: 400px;height: 32px;"
                />
              </el-form-item>
              <el-form-item label="注册城市" prop="regcity">
                <SelectOption class="selectOptionBox" ref="regcitySelectOption" placeHolder="请选择注册城市" title="城市选择"
                    v-model="form.regcityList" selectType="multi" maxSelectLength="2" treeNodeKey="name" :defaultFormValue="regcityDefault" :disabled="['1', '3'].includes(form.validated)"
                    @loadOptions="regcityDataLoad" @chooseError="regcityChooseError" @chooseConfirm="regcityChooseConfirm" v-if="!pageLoading"/>
              </el-form-item>
              <el-form-item label="注册资本" prop="capital">
                <el-input
                    class="inputBox"
                    v-model="form.capital"
                    placeholder="请输入注册资本"
                    clearable
                />
              </el-form-item>
              <el-form-item label="注册资本货币单位" prop="regunit">
                <el-input
                    class="inputBox"
                    v-model="form.regunit"
                    placeholder="请输入注册资本货币单位"
                    clearable
                />
              </el-form-item>
              <el-form-item label="公司介绍" prop="introduce">
                <el-input
                    class="textareaBox"
                    v-model="form.introduce"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入公司介绍"
                />
              </el-form-item>
            </div>
          </div>
          <div class="normalBox">
            <div class="titleBox pageFlex pageAlignCenter">
              <div class="line"></div>
              <div class="title">法定代表人信息</div>
            </div>
            <div class="contentBox bgFF">
              <el-form-item label="法定代表人姓名" prop="legalPerson">
                <el-input
                    class="inputBox"
                    v-model="form.legalPerson"
                    placeholder="请输入法定代表人姓名"
                    clearable
                />
              </el-form-item>
              <el-form-item label="法定代表人身份证" prop="identityCardIsUpload">
                <!-- 电子版（正面） -->
                <div class="imgBox">
                  <div class="pageFlex">
                    <ImageUpload v-model="form.identityCardFront" :isShowTip="false" imgText="身份证人像面照" bg="#FFFFFF"></ImageUpload>
                    <ImageUpload v-model="form.identityCardBack" :isShowTip="false" imgText="身份证国徽面照" bg="#FFFFFF" style="margin-left: 12px;"></ImageUpload>
                  </div>
                  <div class="notice">1.证件照片上的文字需能清晰辨认（支持PNG、JPG和JPEG格式，大小不超过5MB）</div>
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="normalBox">
            <div class="titleBox pageFlex pageAlignCenter">
              <div class="line"></div>
              <div class="title">营业执照</div>
            </div>
            <div class="contentBox bgFF">
              <el-form-item label="营业执照号码" prop="businessLicenseNumber">
                <el-input
                    class="inputBox"
                    v-model="form.businessLicenseNumber"
                    placeholder="请输入营业执照号码"
                    clearable
                />
              </el-form-item>
              <el-form-item label="营业执照登记机关" prop="registrationAuthority">
                <el-input
                    class="inputBox"
                    v-model="form.registrationAuthority"
                    placeholder="请输入营业执照登记机关"
                    clearable
                />
              </el-form-item>
              <el-form-item label="营业截止日期（有效期）" prop="deadline">
                <el-date-picker
                    class="datePicker"
                    v-model="form.deadline"
                    type="date"
                    placeholder="请选择营业截止日期（有效期）"
                    style="width: 400px;height: 32px;"
                />
              </el-form-item>
              <el-form-item label="营业执照副本电子版" prop="businessLicenceCopy">
                <div class="imgBox">
                  <ImageUpload v-model="form.businessLicenceCopy" bg="#FFFFFF"></ImageUpload>
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="normalBox">
            <div class="titleBox pageFlex pageAlignCenter">
              <div class="line"></div>
              <div class="title">税务信息</div>
            </div>
            <div class="contentBox bgFF">
              <el-form-item label="纳税人识别号" prop="taxpayerQualificationCode">
                <el-input
                    class="inputBox"
                    v-model="form.taxpayerQualificationCode"
                    placeholder="请输入纳税人识别号"
                    clearable
                />
              </el-form-item>
              <el-form-item label="纳税登记证电子版" prop="taxCertificatePicture">
                <div class="imgBox">
                  <ImageUpload v-model="form.taxCertificatePicture" bg="#FFFFFF"></ImageUpload>
                </div>
              </el-form-item>
              <el-form-item label="纳税人资格证电子版" prop="taxpayerQualificationCertificate">
                <div class="imgBox">
                  <ImageUpload v-model="form.taxpayerQualificationCertificate" bg="#FFFFFF"></ImageUpload>
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="normalBox">
            <div class="titleBox pageFlex pageAlignCenter">
              <div class="line"></div>
              <div class="title">组织机构</div>
            </div>
            <div class="contentBox bgFF">
              <el-form-item label="组织机构代码" prop="organizationCode">
                <el-input
                    class="inputBox"
                    v-model="form.organizationCode"
                    placeholder="请输入组织机构代码"
                    clearable
                />
              </el-form-item>
              <el-form-item label="组织机构代码证电子版" prop="organizationCodePicture">
                <div class="imgBox">
                  <ImageUpload v-model="form.organizationCodePicture" bg="#FFFFFF" ></ImageUpload>
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="normalBox">
            <div class="titleBox pageFlex pageAlignCenter">
              <div class="line"></div>
              <div class="title">联系信息</div>
            </div>
            <div class="contentBox bgFF">
              <el-form-item label="联系人" prop="contacts">
                <el-input
                    class="inputBox"
                    v-model="form.contacts"
                    placeholder="请输入联系人"
                    clearable
                />
              </el-form-item>
              <el-form-item label="联系电话" prop="telephone">
                <el-input
                    class="inputBox"
                    v-model="form.telephone"
                    placeholder="请输入联系电话"
                    clearable
                />
              </el-form-item>
              <el-form-item label="联系地址" prop="address">
                <el-input
                    class="inputBox"
                    v-model="form.address"
                    placeholder="请输入联系地址"
                    clearable
                />
              </el-form-item>
              <el-form-item label="企业电子邮件" prop="mail">
                <el-input
                    class="inputBox"
                    v-model="form.mail"
                    placeholder="请输入企业电子邮件"
                    clearable
                />
              </el-form-item>
              <el-form-item label="联系邮编" prop="postcode">
                <el-input
                    class="inputBox"
                    v-model="form.postcode"
                    placeholder="请输入联系邮编"
                    clearable
                />
              </el-form-item>
              <el-form-item label="传真" prop="fax">
                <el-input
                    class="inputBox"
                    v-model="form.fax"
                    placeholder="请输入传真"
                    clearable
                />
              </el-form-item>
              <el-form-item label="搜索关键字" prop="keyword">
                <el-input
                    class="inputBox"
                    v-model="form.keyword"
                    placeholder="请输入搜索关键字"
                    clearable
                />
              </el-form-item>
              <el-form-item label="公司主页（网址）" prop="homepage">
                <el-input
                    class="inputBox"
                    v-model="form.homepage"
                    placeholder="请输入公司主页（网址）"
                    clearable
                />
              </el-form-item>
            </div>
          </div>
          <div class="line" v-if="['0', '2'].includes(form.validated)"></div>
          <div class="dataManageBottom pageFlex pageFlexCenter" v-if="['0', '2'].includes(form.validated)">
            <el-button type="primary" :loading="submitLoading" @click="submitNow" v-hasPermi="['gasManage:defaultSetting:companyInfo:add']" v-if="form.validated === '0'">提交审核</el-button>
            <el-button type="primary" :loading="submitLoading" @click="submitNow" v-hasPermi="['gasManage:defaultSetting:companyInfo:edit']" v-if="form.validated === '2'">修改企业信息并重新提交审核</el-button>
          </div>
        </el-form>
      </div>
    </div>
</template>
<script setup>
import ImageUpload from '@/views/gasManage/components/ImageUpload';
import SelectOption from '@/views/gasManage/components/SelectOption';
import { searchManufacturerByIdApi, editManufacturerApi, addManufacturerApi } from '@/api/gasManage/defaultSetting/companyInfo';
import { areasList } from '@/api/system/location';
import {ElLoading, ElMessageBox} from 'element-plus';
import {CircleCheck} from "@element-plus/icons-vue";
import { onMounted } from 'vue';
import { useRoute } from 'vue-router';
import useTagsViewStore from '@/store/modules/tagsView';
const { proxy } = getCurrentInstance();
const { meter_company_type } = proxy.useDict("meter_company_type");
const route = useRoute();
const tagsViewStore = useTagsViewStore();
const pageTitle = ref('资料管理');
const form = ref({
  companyName: '',
  creditCode: '',
  companyType: '',
  location: [],
  province: '',
  city: '',
  district: '',
  size: '',
  business: '',
  mode: '',
  regyear: '',
  regcityList: [],
  regcity: '',
  capital: '',
  regunit: '',
  introduce: '',
  thumb: '',
  legalPerson: '',
  identityCardIsUpload: '',
  identityCardFront: '',
  identityCardBack: '',
  businessLicenseNumber: '',
  registrationAuthority: '',
  deadline: '',
  businessLicenceCopy: '',
  taxpayerQualificationCode: '',
  taxCertificatePicture: '',
  taxpayerQualificationCertificate: '',
  organizationCode: '',
  organizationCodePicture: '',
  contacts: '',
  telephone: '',
  address: '',
  mail: '',
  postcode: '',
  fax: '',
  keyword: '',
  homepage: '',
  validated: '0'
});
const rules = ref({
  companyName: [
    { required: true, message: "企业名称不能为空", trigger: "blur" },
    { min: 2, max: 50, message: '企业名称长度为2-50个字', trigger: 'blur' }
  ],
  companyType: [{ required: true, message: "企业类型不能为空", trigger: "blur" }],
  thumb: [{ required: true, message: "公司LOGO未上传", trigger: "blur" }],
  legalPerson: [{ pattern: /^[\u4e00-\u9fa5·]{2,30}$/, message: '姓名应为2-30个汉字，支持少数民族姓名中的·', trigger: 'blur' }],
  contacts: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
  telephone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  organizationCode: [{pattern: /^[A-Z0-9]{8}-[A-Z0-9]$/, message: '格式为8位数字或大写字母 + 横杠 + 1位数字或大写字母', trigger: 'blur' }],
  mail: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  postcode: [{ pattern: /^[1-9]\d{5}$/, message: '请输入6位数字的邮政编码', trigger: 'blur' }],
})
const submitLoading = ref(false);
//-----------------------------------所属区域选择------------------------
const locationDefault = ref('');
async function locationDataLoad(e){
  const { node, resolve } = e;
  let id = node.level === 0 ? 0 : node.data.id;
  let data = [];
  if(node.data.isEnable != 0){
    if(node.level !== 3){
      data = await areasListApi({parentId: id});
    }
    if(data.length){
      data.map(item=>{
        item.checked = item.isEnable == 0;
        return item
      })
    }
  }
  proxy.$refs.locationSelectOption.handleLoadApi(data, node, resolve);
}
function locationChooseError(e){
  proxy.$modal.msgError('【所属区域】'+e.msg);
}
function locationChooseConfirm(e){
  e.keys.forEach((item, index)=>{
    if(index === 0){
      form.value.province = item;
    }else if(index === 1){
      form.value.city = item;
    }else{
      form.value.district = item;
    }
  })
}
//-----------------------------------注册城市选择------------------------
const regcityDefault = ref('');
async function regcityDataLoad(e){
  const { node, resolve } = e;
  let id = node.level === 0 ? 0 : node.data.id;
  let data = [];
  if(node.data.isEnable != 0){
    if(node.level !== 2){
      data = await areasListApi({parentId: id});
    }
    if(data.length){
      data.map(item=>{
        item.checked = item.isEnable == 0;
        return item
      })
    }
  }
  proxy.$refs.regcitySelectOption.handleLoadApi(data, node, resolve);
}
function regcityChooseError(e){
  proxy.$modal.msgError('【注册城市】'+e.msg);
}
function regcityChooseConfirm(e){
  form.value.regcity = e.keys.join('/');
}
function areasListApi(params){
  return new Promise(resolve=>{
    areasList(params).then(res=>{
      resolve(Array.isArray(res.data) ? res.data : []);
    }).catch(()=>{resolve([])})
  })
}
// -----------------------------------提交-------------------------------
function submitNow(){
  if(submitLoading.value) return;
  if(form.value.identityCardFront && form.value.identityCardBack){
    form.value.identityCardIsUpload = 'true';
  }else{
    form.value.identityCardIsUpload = '';
  }
  let data = JSON.parse(JSON.stringify(form.value));
  delete data.location;
  delete data.regcityList;
  delete data.identityCardIsUpload;
  data.validated = '1';
  proxy.$refs["formRef"].validate((valid)=>{
    if(valid){
      if(form.value.id){
        ElMessageBox.confirm('确认修改企业信息并重新提交审核？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(()=>{
          delete data.userId;
          delete data.updateBy;
          delete data.validatedTime;
          delete data.appId;
          delete data.appSecret;
          delete data.vip;
          delete data.vip_begin_at;
          delete data.vip_end_at;
          delete data.createBy;
          delete data.isEnable;
          delete data.applicationTime;
          editCompanyNow(data);
        }).catch(()=>{})
      }else{
        ElMessageBox.confirm('确认提交新公司申请？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(()=>{
          addCompanyNow(data);
        }).catch(()=>{})
      }
    }else{
      proxy.$modal.alertWarning('您的填写内容有问题！请检查');
    }
  })
}
// -----------------------------------新增-------------------------------
function addCompanyNow(data){
  submitLoading.value = true;
  addManufacturerApi(data).then(() => {
    submitLoading.value = false;
    ElMessageBox.confirm(
        '提交成功',
        '提示',
        {
          type: 'success',
          icon: markRaw(CircleCheck),
          showCancelButton: false
        }
    ).then(()=>{
      toBack();
    })
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// -----------------------------------修改-------------------------------
function editCompanyNow(data){
  submitLoading.value = true;
  editManufacturerApi(data).then(()=>{
    submitLoading.value = false;
    ElMessageBox.confirm(
        '提交成功',
        '提示',
        {
          type: 'success',
          icon: markRaw(CircleCheck),
          showCancelButton: false
        }
    ).then(()=>{
      toBack();
    })
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// -----------------------------------查询-------------------------------
onMounted(()=>{
  if(route.params.companyId && route.params.companyId !== ''){
    form.value.id = route.params.companyId;
    initData();
  }else{
    pageTitle.value = '新增企业';
    route.meta.title = pageTitle.value;
    route.title = pageTitle.value;
    tagsViewStore.updateVisitedView(route);
  }
})
const pageLoading = ref(false);
async function initData(){
  pageLoading.value = true;
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  let data = await getCompanyInfoApi(form.value.id);
  if(data){
    data.validated = String(data.validated);
    if(data.province){
      data.location = [data.province, data.city, data.district];
      locationDefault.value = data.location.join('/');
    }
    if(data.regcity){
      regcityDefault.value = data.regcity;
      data.regcityList = data.regcity.split('/');
    }
    form.value = data;
    loading.close();
    pageLoading.value = false;
  }else{
    loading.close();
    pageLoading.value = false;
    setTimeout(()=>{
      toBack();
    }, 500)
  }
}
function getCompanyInfoApi(id){
  return new Promise((resolve, reject) => {
    searchManufacturerByIdApi(id).then(res => {
      resolve(res.data)
    }).catch(()=>{
      resolve(false);
    })
  })
}
function toBack(){
  const obj = { path: "/gasManage/defaultSetting/companyInfo" };
  proxy.$tab.closeOpenPage(obj);
}
</script>
<style lang="scss" scoped>
@import "@/assets/styles/public.scss";
$inputBoxWidth: 400px;
:deep(.el-input){
    .el-input__wrapper{
        background-color: $formBgSet;
        box-shadow: none;
    }
}
:deep(.el-select){
    .el-select__wrapper{
        background-color: $formBgSet;
        box-shadow: none;
    }
}
:deep(.el-textarea){
    .el-textarea__inner{
        background-color: $formBgSet;
        box-shadow: none;
    }
}
.app-container{
    width: 100%;
    background: $formBgset4;
    min-height: calc(100vh - $navBarHeight);
    .dataManage{
        width: 100%;
        min-height: 100%;
        border-radius: 6px;
        box-sizing: border-box;
        padding-top: 20px;
        .dataManageTop{
            width: calc(100% - 40px);
            height: 40px;
            margin: 0 auto;
            .itemBox{
                width: calc((100% - 10px) / 3);
                height: 100%;
                position: relative;
                background: #F7F8FA;
                margin-right: 2px;
                font-weight: 500;
                font-size: 16px;
                color: #4E5969;
                line-height: 40px;
                box-sizing: border-box;
                padding-left: 30px;
                .sanBox{
                    width: 28px;
                    height: 28px;
                    background: #F7F8FA;
                    transform-origin: center center;
                    transform: rotate(45deg);
                    position: absolute;
                    top: 6px;
                    right: -14px;
                    z-index: 1;
                }
                .whiteSanBox{
                    width: 28px;
                    height: 28px;
                    background: #FFFFFF;
                    transform-origin: center center;
                    transform: rotate(45deg);
                    position: absolute;
                    top: 6px;
                    left: -14px;
                }
                &:first-child{
                    padding-left: 16px;
                }
                &.active{
                    background: var(--el-color-primary);
                    color: #FFFFFF;
                    .sanBox{
                        background: var(--el-color-primary);
                    }
                }
            }
        }
        .dataManageContent{
            width: 100%;
            padding: 0 20px;
            margin-top: 24px;
            .normalBox{
                width: 100%;
                border: 1px solid $borderColor;
                margin-bottom: 24px;
                .titleBox{
                    width: 100%;
                    height: 44px;
                    background: $formBgset3;
                    padding-left: 8px;
                    box-sizing: border-box;
                    .line{
                        width: 4px;
                        height: 16px;
                        background: $formBgset2;
                        margin-right: 8px;
                    }
                    .title{
                        height: 16px;
                        line-height: 16px;
                        font-weight: 500;
                        font-size: 16px;
                        color: #1D2129;
                    }
                }
                .contentBox{
                    width: 100%;
                    padding: 24px 0;
                    .inputBox{
                        width: $inputBoxWidth;
                        height: 32px;
                    }
                    .textareaBox{
                        width: $inputBoxWidth;
                    }
                    .selectOptionBox{
                      width: $inputBoxWidth;
                    }
                    .multiSelection{
                      width: $inputBoxWidth;
                      height: 32px;
                      margin-right: 10px;
                      margin-bottom: 10px;
                    }
                    .imgBox{
                        min-width: $inputBoxWidth;
                        background: $formBgSet;
                        border-radius: 4px;
                        padding: 12px;
                        .notice{
                            height: 20px;
                            font-weight: 400;
                            font-size: 12px;
                            color: #86909C;
                            line-height: 20px;
                            margin-top: 12px;
                        }
                    }
                }
            }
        }
        .line{
            width: 100%;
            height: 3px;
            background-color: $formBgset4;
        }
        .dataManageBottom{
            width: 100%;
            height: 72px;
        }
    }
}
</style>